/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */
#include <gio/gio.h>
#include <gio-unix-2.0/gio/gdesktopappinfo.h>

#include "app-manager.h"
#include "basic-app-model.h"

#include <QDebug>
#include <QDBusReply>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QProcess>

#define KYLIN_APP_MANAGER_NAME         "com.kylin.ProcessManager"
#define KYLIN_APP_MANAGER_PATH         "/com/kylin/ProcessManager/AppLauncher"
#define KYLIN_APP_MANAGER_INTERFACE    "com.kylin.ProcessManager.AppLauncher"

namespace UkuiMenu {
AppManager *AppManager::instance()
{
    static AppManager instance(nullptr);
    return &instance;
}

AppManager::AppManager(QObject *parent) : QObject(parent)
{

}

void AppManager::launchApp(const QString &desktopFilePath)
{
    if (desktopFilePath.isEmpty()) {
        return;
    }

    Q_EMIT request(UkuiMenuApplication::Hide);

    QDBusMessage message = QDBusMessage::createMethodCall(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, "LaunchApp");
    message << desktopFilePath;

    auto watcher = new QDBusPendingCallWatcher(QDBusPendingCall(QDBusConnection::sessionBus().asyncCall(message)), this);
    QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [desktopFilePath] (QDBusPendingCallWatcher *self) {
        if (self->isError()) {
//            QString cmd = parseDesktopFile(desktopFilePath);
//            if (!cmd.isEmpty()) {
//                QProcess::startDetached(cmd, QStringList());
//            }
            GDesktopAppInfo *desktopAppInfo = g_desktop_app_info_new_from_filename(desktopFilePath.toLocal8Bit().data());
            if (desktopAppInfo == nullptr) {
                return;
            }
            bool launched = g_app_info_launch(G_APP_INFO(desktopAppInfo), nullptr, nullptr, nullptr);
            g_object_unref(desktopAppInfo);
            qDebug() << "launch with GDesktopAppInfo:" << launched;
        }
        self->deleteLater();
    });

    BasicAppModel::instance()->databaseInterface()->updateApLaunchedState(desktopFilePath, true);
}

void AppManager::launchBinaryApp(const QString &app, const QString &args)
{
    if (app.isEmpty()) {
        return;
    }

    QDBusMessage message = QDBusMessage::createMethodCall(KYLIN_APP_MANAGER_NAME, KYLIN_APP_MANAGER_PATH, KYLIN_APP_MANAGER_INTERFACE, "LaunchApp");
    message << app << args;

    auto watcher = new QDBusPendingCallWatcher(QDBusPendingCall(QDBusConnection::sessionBus().asyncCall(message)), this);
    QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [app, args] (QDBusPendingCallWatcher *self) {
        if (self->isError()) {
            QProcess::startDetached(app, {args}, "");
        }
        self->deleteLater();
    });
}

void AppManager::launchAppWithArguments(const QString &desktopFile, const QStringList &args, const QString &applicationName)
{
    QDBusMessage message = QDBusMessage::createMethodCall(KYLIN_APP_MANAGER_NAME,
                                                          KYLIN_APP_MANAGER_PATH,
                                                          KYLIN_APP_MANAGER_INTERFACE,
                                                          "LaunchAppWithArguments");
    message << desktopFile << args;

    auto watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message), this);
    connect(watcher, &QDBusPendingCallWatcher::finished, this, [applicationName, args] (QDBusPendingCallWatcher *self) {
        if (self) {
            QDBusPendingReply<QString, QByteArray> reply = *self;
            if (self->isError()) {
                qWarning() << reply.error().message();
                QProcess::startDetached(applicationName, args);
            }
            self->deleteLater();
        }
    });
}

void AppManager::changeFavoriteState(const QString &appid, bool isFavorite)
{
    BasicAppModel::instance()->databaseInterface()->fixAppToFavorite(appid, isFavorite ? 1 : 0);
}

QString AppManager::parseDesktopFile(const QString &desktopFilePath)
{
    // TODO: try QSettings?
    GKeyFile *keyFile = g_key_file_new();
    gboolean res = g_key_file_load_from_file(keyFile, desktopFilePath.toUtf8(), G_KEY_FILE_NONE, nullptr);
    if (!res) {
        return "";
    }

    gchar *exec = g_key_file_get_value(keyFile, "Desktop Entry", "Exec", nullptr);
    if (!exec) {
        g_key_file_free(keyFile);
        return "";
    }

    QStringList stringList = QString(exec).split(" ");

    g_free(exec);
    g_key_file_free(keyFile);

    if (stringList.isEmpty()) {
        return "";
    }

    QString program = stringList.first();
    stringList.removeFirst();

    // TODO: freedesktop group
    for (const auto &str : stringList) {
        if (!str.startsWith("%")) {
            program.append(" " + str);
        }
    }

    return program;
}

} // UkuiMenu
